<?php
class Prescription extends ORDataObject{
	var $prescription_id 	= 	'';
	var $doctor_id 			= 	'';
	var $medical_record_id 	= 	'';
	var $date 				= 	'';
	var	$insurance_price	=	'';
	var $re_examine 		= 	'';
	var $note 				= 	'';
	var $diagnosis          =   '';
	
	
	var $_table = 'prescription';
	var $_key = 'prescription_id';
	var $_internalName = 'Prescription';
	var $dateformat = '';
	
	function Prescription(){
		parent::ORDataObject();
		$this->dateformat	=	L10nHelper::getSqlDateFormat();
	}
	
	/**
	 * Object should be populated before calling this function
	 *
	 * @param int $templateId
	 */
	public function copyFromPrescriptionTemplate($templateId) {		
		$res = Celini::newORDO('TemplateItem')->getTemplateItems($templateId);
		$mp = Celini::newORDO('MedicinePrice');
		foreach ($res as $item) {			
			$unitPrice = $mp->getPrice($item['medicine_id']);
			$price = $unitPrice * $item['quantity_num'];
			$data = array(
				'prescription_id' 	=> $this->get_id(),
				'medicine_id'		=> $item['medicine_id'],
				'usage_title'		=> $item['usage_title'],
				'usage_num'			=> $item['usage_num'],
				'dosage'			=> $item['dosage'],
				'time'				=> $item['time'],
				'quantity_num'		=> $item['quantity_num'],
				'quantity_title'	=> $item['quantity_title'],
				'note'				=> $item['note'],
				'price'				=> $price);
			$pi = Celini::newORDO('PrescriptionItem'); 	
			$pi->addNewPrescriptionItem($data);
		}
	}
	
	public function getPatient($prescriptionId) {
		$pres = Celini::newORDO('Prescription', $prescriptionId);
		$emrId = $pres->get('medical_record_id');
		$emr = Celini::newORDO('MedicalRecord', $emrId);
		return $emr->get('patient_id'); 
	}
	
	public function getAllItems($prescriptionId) {
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "pi.medicine_id, pi.quantity_num, mp.price, mp.insurance_support",
			'from' 		=> "prescription_item pi				
				INNER JOIN medicine_price mp on pi.medicine_id = mp.medicine_id", 			
			'where' 	=> "pi.prescription_id = $prescriptionId"
			);
		$ds->setup($this->_db,$sql);
		return $ds->toArray();
	}
	
	function addNewPrescription($pres){				
		$data = array (
				'doctor_id' 		=> 	$pres['doctor_id'],
				'medical_record_id'	=> 	$pres['medical_record_id'],
				'note'				=> 	$pres['note'],
				're_examine'		=> 	$pres['re_examine'],
				'date'				=>  date('Y-m-d'),
		        'diagnosis'         =>  $pres['diagnosis']
			);		
		$this->populateArray($data);		
		$this->persist();
		return $this->prescription_id;		
	}

	function updatePrescription($pres){                
        $data = array (
                'doctor_id'         =>  $pres['doctor_id'],
                'medical_record_id' =>  $pres['medical_record_id'],
                'note'              =>  $pres['note'],
                're_examine'        =>  $pres['re_examine'],
                'diagnosis'         =>  $pres['diagnosis']                
            );      
        $this->populateArray($data);        
        $this->persist();
        return $this->prescription_id;      
    }   
			
	function updateInfo($info){
		// if re_examine is updated
		if ($info['whichfield'] == 're_examine') $info['new_value'] = $this->convertDate($info['new_value']);
		$sql = "UPDATE prescription SET ".
			$info['whichfield']. " = '".$info['new_value'] .
			"' WHERE prescription_id = '" .$info['id']."'";	
		$this->_execute($sql);
	}
	
	function delete($prescriptionID){		
		Celini::newORDO('PrescriptionItem')->delete($prescriptionID);

		$sql = "DELETE FROM prescription WHERE prescription_id = '$prescriptionID'";
		$this->_execute($sql);		
		return $prescriptionId;
	}	
	
	function getPrescription($prescriptionId){
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "prescription_id,medical_record_id, doctor_id, pe.name doctor_name, date, note , re_examine, diagnosis",
			'from' 		=> "prescription pr LEFT JOIN employee pe ON (pr.doctor_id=pe.person_id)", 			
			'where' 	=> "prescription_id = '$prescriptionId'"
			);
	
		$ds->setup($this->_db,$sql);
		$result = $ds->toArray();
		if (!empty($result)) return $result[0];
		return $result;		
	}
	
	function getPrescriptionID($recordID, $doctorID){
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "prescription_id",
			'from' 		=> "prescription",
			'where' 	=> "medical_record_id = '$recordID'"
			);
					
		$ds->setup($this->_db,$sql);
		$result = $ds->toArray('prescription_id');
		if (empty($result)){
			return false;
		} else return $result[0];	
	}
	
    function listPrescriptions($recordID){
        $ds = new Datasource_sql();
        $sql = array(
            'cols'      => "prescription_id, doctor_id, date, pe.name doctor_name",
            'from'      => "prescription pr LEFT JOIN employee pe ON (pr.doctor_id=pe.person_id)",
            'where'     => "medical_record_id = '$recordID'"
            );
                    
        $ds->setup($this->_db,$sql);
        $result = $ds->toArray();
        return $result;   
    }
	
	function getPrescriptionIdFromRecord($recordId){
		$sql = "SELECT prescription_id FROM $this->_table WHERE medical_record_id = ".(int)$recordId;
		$res = $this->_execute($sql);
		if ($res && !$res->EOF) {
			return $res->fields['prescription_id'];
		}
		return false;	
	}	
	
	public function getPrescriptionIdFromTicketItem($itemId) {
		$sql = "SELECT prescription_id FROM $this->_table p
		        LEFT JOIN medical_record mr ON p.medical_record_id = mr.medical_record_id
		        LEFT JOIN ticket_item ti ON mr.ticket_id = ti.ticket_id
		        WHERE ti.ticket_item_id = $itemId";
		$res = $this->_execute($sql);
		if (empty($res)) {
			return 0;
		}
		return $res->fields['prescription_id'];
	}
	
	public function updateDoctorId($doctorId, $presId) {
		$this->_execute("UPDATE $this->_table SET doctor_id = $doctorId WHERE prescription_id = $presId");
	}
	
	private function convertDate($vnDate){
		$new = '0000-00-00';
		if (preg_match('/^(\d{1,2})[\/-](\d{1,2})[\/-](\d{2,4})$/', $vnDate)){
			$xdate=&new DateObject();
			$new = $xdate->createFromVN($vnDate);	
			return $new->toISO();
		}		
	}

	
	public function getLatestObjectByPatientId($patientId){
		$sql = "SELECT max(p.$this->_key) as $this->_key
				FROM $this->_table p LEFT JOIN medical_record mr ON (p.medical_record_id = mr.medical_record_id)		
				WHERE mr.patient_id = $patientId";
		$res = $this->_execute($sql);
		if (empty($res) || $res->fields[$this->_key] == '') {
			return '';
		}
		$obj	=	Celini::newORDO('Prescription',$res->fields[$this->_key]);
		return $obj;
	}
	
	public function getPrice($presId){
		$sql	=	"SELECT sum(price) as price 
					 FROM prescription_item WHERE prescription_id=".(int)$presId;
		$res	=	$this->_execute($sql);
		if (empty($res)){
			return 0;
		}
		return $res->fields['price'];
	}
	
	// PPDong, 2009-06-17
	public function getInsurancePrice(){
		return $this->insurance_price;
	}
	
	public function updateData($data){
		if(count($data) > 0){
			$sql	=	"UPDATE $this->_table";
			$sql	.=	" SET ";
			foreach($data as $key => $value){
				$sql	.=	"$key='$value',";
			}
			$sql	=	substr($sql,0,strlen($sql)-1);
			$sql	.=	" WHERE $this->_key=".(int)$this->prescription_id;
			$this->_execute($sql);
		}
	}
}
?>